package com.ebupt.migu.music.schedule.service.impl;

import com.ebupt.migu.music.common.util.CSVUtils;
import com.ebupt.migu.music.roster.utils.ESutils;
import com.ebupt.migu.music.schedule.mapper.RosterTaskMapper;
import com.ebupt.migu.music.schedule.service.RosterTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Intellij IDEA.
 * User:  liuyangyang@cd.ebupt.com
 * Date:  2020/4/29
 */
@Slf4j
@Service
public class RosterTaskServiceImpl implements RosterTaskService {

    @Autowired
    private RosterTaskMapper rosterTaskMapper;
    @Autowired
    private ESutils eSutils;

    /**
     * 创建待反查
     */
    @Override
    public void doRoster() {
        // 查询创建待反查的名单信息
        List<HashMap<String, Object>> rosters = rosterTaskMapper.queryRostersByStatus();
        if (rosters.size() == 0) {
            return;
        }
        // 遍历，完成反查
        for (HashMap<String, Object> roster : rosters) {
            log.info("{}: 开始反查", roster.get("rosterName"));
            // 名单ID
            String rosterId = String.valueOf(roster.get("id"));
            // 文件路径
            String path = String.valueOf(roster.get("path"));
            if (StringUtils.isBlank(path)) {
                continue;
            }
            List<String[]> records = CSVUtils.csvRead(path, ',');
            // 文件首行内容为模板内容
            if (records == null || records.size() < 2) {
                continue;
            }
            // 移除表头
            records.remove(0);
            // list转set，元素剔重
            Set<String[]> sets = new HashSet<>(records);
            // 遍历反查并插入roster_info表中
            for (String[] record : sets) {
                // 数据列不能为空
                if(record.length<2){
                    continue;
                }
                if (null == record[1]) {
                    continue;
                }
                String memberType = String.valueOf(roster.get("memberType"));
                // 跳过重复名单
                Map<String, Object> mapRoster = new HashMap<>();
                mapRoster.put("rosterId", rosterId);
                mapRoster.put("paramValue", record[1].trim());
                mapRoster.put("memberType", memberType);
                if (rosterTaskMapper.isUuidOrMsisdnExist(mapRoster)) {
                    log.info("{}已经存在于名单中", record[1]);
                    continue;
                }
                Map<String, Object> map = new HashMap<>();
                map.put("rosterId", rosterId);
                // csv模板表头格式： 姓名, 手机号/uid, 备注
                map.put("name", record[0]);
                map.put("desc", record[2]);
                map.putAll(eSutils.inverse_search(record[1].trim(), memberType));
                rosterTaskMapper.addRosterInfo(map);
            }
            // 将当前名单状态修改成反查完成
            Map<String, Object> map = new HashMap<>();
            map.put("rosterId", rosterId);
            map.put("status", "1");
            rosterTaskMapper.updateRosterStatusByRosterID(map);
            log.info("{}: 反查完成", roster.get("rosterName"));
        }
    }

    /**
     * 追加待反查
     */
    @Override
    public void doRosterExtend() {
        // 查询追加待反查的列表
        List<HashMap<String, Object>> rosterExtends = rosterTaskMapper.queryRostersExtendByStatus();
        if (rosterExtends.size() == 0) {
            return;
        }
        for (HashMap<String, Object> extend : rosterExtends) {
            // 名单ID
            String rosterId = String.valueOf(extend.get("rosterId"));
            log.info("{}: 开始反查", rosterId);
            String path = String.valueOf(extend.get("path"));
            List<String[]> records = CSVUtils.csvRead(path, ',');
            // 文件首行内容为模板内容
            if (records == null || records.size() < 2) {
                continue;
            }
            // 移除表头
            records.remove(0);
            // list转set，元素剔重
            Set<String[]> sets = new HashSet<>(records);
            // 遍历反查并插入roster_info表中
            for (String[] record : sets) {
                if (null == record[1]) {
                    continue;
                }
                String memberType = String.valueOf(extend.get("type"));
                // 跳过重复名单
                Map<String, Object> mapRoster = new HashMap<>();
                mapRoster.put("rosterId", rosterId);
                mapRoster.put("paramValue", record[1].trim());
                mapRoster.put("memberType", memberType);
                if (rosterTaskMapper.isUuidOrMsisdnExist(mapRoster)) {
                    log.info("{}已经存在于名单中", record[1].trim());
                    continue;
                }
                Map<String, Object> map = new HashMap<>();
                map.put("rosterId", rosterId);
                // csv模板表头格式： 姓名, 手机号/uid, 备注
                map.put("name", record[0]);
                map.put("desc", record[2]);
                map.putAll(eSutils.inverse_search(record[1].trim(), memberType));
                rosterTaskMapper.addRosterInfo(map);
            }
            // 将当前名单状态修改成反查完成
            Map<String, Object> map = new HashMap<>();
            map.put("id", extend.get("id"));
            rosterTaskMapper.updateRosterExtendStatusByID(map);
            log.info("{}: 反查完成", extend.get("rosterId"));
        }
    }

    /**
     * 每日更新
     */
    @Override
    public void doDaily() {
        // 将黑白名单列表中状态为1-反查完成/3-更新完成的名单状态修改为2-等待每日更新
        rosterTaskMapper.updateRosterStatusForDailyUpdate();
        // 查询状态为2-等待每日更新的id
        List<String> rosterIds = rosterTaskMapper.queryRosterIDs();
        if (rosterIds == null || rosterIds.size() == 0) {
            return;
        }
        // 遍历更新名单
        for (String rosterId : rosterIds) {
            // 查询当前名单下的成员
            Map<String, Object> mapRosterId = new HashMap<>();
            mapRosterId.put("rosterId", rosterId);
            List<HashMap<String, Object>> infos = rosterTaskMapper.queryRostersForDailyUpdate(mapRosterId);
            if (infos == null || infos.size() == 0) {
                continue;
            }
            // 反查并逐个更细每个成员
            // 每日更新只通过手机号码进行更新反查
            for (Map<String, Object> info : infos) {
                if (null == info.get("msisdn")) {
                    continue;
                }
                String msisdn = String.valueOf(info.get("msisdn"));
                String id = String.valueOf(info.get("id"));
                Map<String, Object> inverse = eSutils.inverse_search(msisdn, "1");
                inverse.put("id", id);
                if ((StringUtils.isBlank(String.valueOf(inverse.get("uuid"))) &&
                        StringUtils.isBlank(String.valueOf(inverse.get("imei"))) &&
                        StringUtils.isBlank(String.valueOf(inverse.get("idfa")))) ||
                        (StringUtils.isBlank(String.valueOf(inverse.get("msisdn"))) &&
                                StringUtils.isBlank(String.valueOf(inverse.get("imei"))) &&
                                StringUtils.isBlank(String.valueOf(inverse.get("idfa"))))) {
                    continue;
                }
                rosterTaskMapper.updateRosterInfoByID(inverse);
            }
            // 将当前名单状态修改为3-更新完成
            Map<String, Object> roster = new HashMap<>();
            roster.put("rosterId", rosterId);
            roster.put("status", 3);
            rosterTaskMapper.updateRosterStatusByRosterID(roster);
        }
    }
}
